import { ElMessage } from 'element-plus'// 下载excel表格
export default function downloadFile(res, type,fileName) {
  // console.log('res.headers',res.headers);
  // let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
  // if (!fileName) {
  //   fileName = decodeURI(
  //     escape(res.headers["content-disposition"].split("=")[1])
  //   );
  // }
  // if ("msSaveOrOpenBlob" in navigator) {
  //   window.navigator.msSaveOrOpenBlob(blob, fileName);
  // } else {
  //   const elink = document.createElement("a");
  //   elink.download = fileName;
  //   elink.style.display = "none";
  //   elink.href = URL.createObjectURL(blob);
  //   document.body.appendChild(elink);
  //   elink.click();
  //   URL.revokeObjectURL(elink.href);
  //   document.body.removeChild(elink);
  // }
  if (!res.headers) {
    const reader = new FileReader()
    reader.onload = () => {
      try {
        const res = JSON.parse(reader.result)
        ElMessage.error(res.msg)
        // 在这里处理 JSON 数据
      } catch (error) {
        console.error('Error parsing JSON:', error)
      }
    }
    return reader.readAsText(res)
  }
  let blob = null
  if (type == "excel") blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
  if (type == "zip") blob = new Blob([res.data], { type: 'application/zip' })
  const contentDisposition = res.headers['content-disposition']

  if (!fileName) {
    fileName = contentDisposition.split('=')[1].replace(/['"]/g, '')
    fileName = decodeURI(fileName)
  }
  if ('msSaveOrOpenBlob' in navigator) {
    window.navigator.msSaveOrOpenBlob(blob, fileName)
  } else {
    const elink = document.createElement('a')
    elink.download = fileName
    elink.style.display = 'none'
    elink.href = URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink)
  }
}
